package ru.ifmo.filemanager.ftpplugin;

import java.io.IOException;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTPClient;

import ru.ifmo.filemanager.filesystem.Type;
import ru.ifmo.filemanager.filesystem.abstractplugin.AbstractDirectory;
import ru.ifmo.filemanager.filesystem.interfaces.DirectoryListReceiver;
import ru.ifmo.filemanager.filesystem.interfaces.FileSystemObject;

public class FtpTopDirectory extends AbstractDirectory {

	private final String serverName;
	private final FTPClient client;
	
	private FtpTopDirectory(String serverName, FtpRootDirectory root, FTPClient client) {
		super();
		this.serverName = serverName;
		this.client = client;
	}

	@Override
	public String[] list() throws IOException {			
		
		String[] result = client.listNames();
		
		return result;
	}

	@Override
	public FileSystemObject lookup(String name) throws IOException {
		
		System.out.println("lookup in " + name);
		
		return new FtpChildDirectory(name, "", this);
	}

	@Override
	public void dispose() {
	}

	@Override
	public Type type() {
		return Type.DIRECTORY;
	}

	public static FtpTopDirectory connectTo(String serverName,
			FtpRootDirectory root) {
		FTPClient client = new FTPClient();

		try {
			client.connect(serverName);
			
			boolean login = client.login("anonymous", "12345");
			
			if( !login )
				return null;
			
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			
			return null;
		}
		
		return new FtpTopDirectory(serverName, root, client);
	}

	public final String getServerName() {
		return serverName;
	}

	@Override
	public final String getName() {
		return serverName;
	}
	
	public final String[] list( String fullPath )
	{
		try {
			return client.listNames(fullPath);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
			return null;
		}
	}
}
